package com.bbh.plugin.single.privilege.demo.controller;

import com.bbh.plugin.single.privilege.core.entity.Account;
import com.bbh.plugin.single.privilege.core.entity.Area;
import com.bbh.plugin.single.privilege.core.entity.Organization;
import com.bbh.plugin.single.privilege.core.enums.BaseEnum;
import com.bbh.plugin.single.privilege.core.enums.OrganizationEnum;
import com.bbh.plugin.single.privilege.core.service.AccountService;
import com.bbh.plugin.single.privilege.core.service.AreaService;
import com.bbh.plugin.single.privilege.core.service.OrganizationService;
import com.bbh.plugin.single.privilege.core.vo.tree.OrganizationVo;
import com.bbh.plugin.single.privilege.core.vo.tree.TreeTableVo;
import com.bbh.plugin.single.privilege.core.vo.tree.ZTreeNoneAjaxVo;
import com.bbh.common.domain.Condition;
import com.bbh.common.domain.Message;
import com.bbh.common.domain.StatusType;
import com.bbh.common.utils.IdUtils64;
import com.bbh.common.utils.mapper.JsonMapper;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.EnumSet;
import java.util.List;

/**
 * 机构Controller
 *
 * @author ThinkGem
 * @version 2013-5-15
 */
@Controller
@RequestMapping(value = "/organization")
public class OrganizationController extends BasicController {

    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private AreaService areaService;
    @Autowired
    private AccountService accountService;


    /**
     * 跳转菜单页面
     *
     * @author bestgwd
     */
    @RequestMapping(value = VIEW_FILED + "/index")
    public String index(ModelMap model) {
        return "single/organization/index";
    }

    @RequestMapping(value = INSERT_FILED + "/toAdd")
    public String toAdd(String idField, String textField) {
        return "single/organization/add";
    }

    /**
     * 跳转增加菜单页面
     *
     * @param
     * @return
     */
    @RequestMapping(value = UPDATE_FILED + "/edit")
    public String toAddResource(ModelMap model, @RequestParam(value = "id") String id, String type) {
        if ("add".equals(type)) {
            if (StringUtils.isNotBlank(id) && !"0".equals(id)) {
                Organization organization = organizationService.selectByPrimaryKey(id);
                Area area = areaService.selectByPrimaryKey(organization.getAreaId());
                model.addAttribute("area", area);
                model.addAttribute("org", organization);
            }
            model.addAttribute(OPERATE_TYPE, "add");
        }
        if ("edit".equals(type)) {
            Organization organization = organizationService.selectByPrimaryKey(id);
            String code = organization.getCode();
            if (code.length() > 4) {
                code = code.substring(code.length() - 4, code.length());
            }
            organization.setCode(code);
            Organization parentOranization = organizationService.selectByPrimaryKey(organization.getParentId());
            Area area = areaService.selectByPrimaryKey(organization.getAreaId());
            Account primaryAccount = accountService.selectByPrimaryKey(organization.getPrimaryPersonId());
            Account deputyAccount = accountService.selectByPrimaryKey(organization.getDeputyPersonId());
            model.addAttribute("area", area);//地区
            model.addAttribute("org", parentOranization);//上级机构
            model.addAttribute("organization", organization);//当前机构
            model.addAttribute("primaryUser", primaryAccount);//主负责人
            model.addAttribute("deputyUser", deputyAccount);//副负责人
            model.addAttribute(OPERATE_TYPE, "edit");
        }
        model.addAttribute("orgType", EnumSet.allOf(OrganizationEnum.ORGTYPE.class));
        model.addAttribute("orgGrade", EnumSet.allOf(OrganizationEnum.ORGGRADE.class));
        return "single/organization/edit";
    }


    @RequestMapping(VIEW_FILED + "/treeData")
    public
    @ResponseBody
    List orgZtree(String orgId) throws ServletRequestBindingException {

        Condition condition = new Condition();
        condition.put("dataStatus", BaseEnum.DATA_STATUS.NORMAL.getKey());
        List<ZTreeNoneAjaxVo> list = organizationService.selectTreeOrganizationChildren(condition);
        return list;
    }


    @RequestMapping(value = INSERT_FILED+"/insert")
    public
    @ResponseBody
    Message insert(Organization organization) {
        Date date = new Date();
        organization.setId(IdUtils64.getInstance().getStringId());
        organization.setCreateBy(getLoginName());
        organization.setCreateTime(date);
        organization.setModifyBy(getLoginName());
        organization.setModifyTime(date);
        organization.setDataStatus(BaseEnum.DATA_STATUS.NORMAL.getKey());
        if (!"-1".equals(organization.getParentId())) {
            Organization parentOrg = organizationService.selectByPrimaryKey(organization.getParentId());
            String code = parentOrg.getCode() + organization.getCode();
            organization.setCode(code);
        }
        organizationService.insert(organization);
        return new Message(StatusType.SUCCESS.getKey(), "增加成功");
    }

    @RequestMapping(DELETE_FILED + "/delete")
    public
    @ResponseBody
    Message delete(@RequestParam(value = "ids[]") String[] ids) {
        if (ArrayUtils.isNotEmpty(ids)) {
            for (String id : ids) {
                Organization organization = organizationService.selectByPrimaryKey(id);
                if (organization != null) {
                    organization.setDataStatus(BaseEnum.DATA_STATUS.DELETE.getKey());//设置为不可用
                    organization.setModifyBy(getLoginName());
                    organization.setModifyTime(new Date());
                    organizationService.updateByPrimaryKeySelective(organization);
                }
            }
        }

        return new Message(StatusType.SUCCESS.getKey(), "删除成功");
    }

    /**
     * update
     *
     * @return
     */
    @RequestMapping(UPDATE_FILED + "/update")
    public
    @ResponseBody
    Message update(@Valid Organization organization) {
        Assert.notNull(organization.getId(), "参数错误");
        Organization modifyOrganization = organizationService.selectByPrimaryKey(organization.getId());
        if (modifyOrganization != null) {
            modifyOrganization.setModifyBy(getLoginName());
            modifyOrganization.setModifyTime(new Date());
            modifyOrganization.setIsEnabled(organization.getIsEnabled());
            modifyOrganization.setEmail(organization.getEmail());
            modifyOrganization.setAddress(organization.getAddress());
            modifyOrganization.setAreaId(organization.getAreaId());
            modifyOrganization.setDeputyPersonId(organization.getDeputyPersonId());
            modifyOrganization.setDescription(organization.getDescription());
            modifyOrganization.setPrimaryPersonId(organization.getPrimaryPersonId());
            modifyOrganization.setGrade(organization.getGrade());
            modifyOrganization.setFax(organization.getFax());
            modifyOrganization.setMaster(organization.getMaster());
            modifyOrganization.setName(organization.getName());
            modifyOrganization.setParentId(organization.getParentId());
            modifyOrganization.setPhone(organization.getPhone());
            modifyOrganization.setZipCode(organization.getZipCode());
            modifyOrganization.setSort(organization.getSort());
            modifyOrganization.setType(organization.getType());
            if ("-1".equals(organization.getParentId())) {
                modifyOrganization.setCode(organization.getCode());
            } else {
                Organization parentOrganization = organizationService.selectByPrimaryKey(organization.getParentId());
                modifyOrganization.setCode(parentOrganization.getCode() + organization.getCode());
            }
            organizationService.updateByPrimaryKeySelective(modifyOrganization);
        }
        return new Message(StatusType.SUCCESS.getKey(), "更新成功");
    }

    /**
     * 获取菜单列表
     *
     * @param request
     * @param model
     * @param id
     * @param name
     * @return
     * @throws org.springframework.web.bind.ServletRequestBindingException
     */
    @RequestMapping(VIEW_FILED + "/list")
    @ResponseBody
    public TreeTableVo list1(HttpServletRequest request, Model model, String id, String name, String isEnabled) throws ServletRequestBindingException {
        Condition condition = new Condition();
        condition.put("dataStatus", BaseEnum.DATA_STATUS.NORMAL.getKey());
        condition.put("parentId", null == id ? -1 : id);
        List<OrganizationVo> list = organizationService.findList(condition);
        TreeTableVo treeTableVo = new TreeTableVo();
        treeTableVo.setRows(list);
        return treeTableVo;
    }


    @RequestMapping(VIEW_FILED+"/toUserList")
    public String toUserList(String callback,String name) {
      return "account/treeList";
    }

    @RequestMapping(VIEW_FILED+"/userTreeList")
    @ResponseBody
    public String treeList(String callback,String name) {
        Condition condition = new Condition();
        if (StringUtils.isNotBlank(name)) {
            condition.put("orgName", name);
        }
        List<ZTreeNoneAjaxVo> list = organizationService.selectTreeOrganizationChildren(condition);

        return JsonMapper.nonEmptyMapper().toJsonP(callback, list);
    }
    @RequestMapping(VIEW_FILED+"/toTreeList")
    public String toTreeList(String callback,String name) {
        return "single/organization/treeList";
    }

    @RequestMapping("/view/treeList")
    @ResponseBody
    public String treeList(String callback,String name,String id) {
        Condition condition = new Condition();
        if (StringUtils.isNotBlank(name)) {
            condition.put("orgName", name);
        }
        if (StringUtils.isNotBlank(id)) {
            condition.put("comId", id);
        }
        condition.put("dataStatus", BaseEnum.DATA_STATUS.NORMAL.getKey());
        List<ZTreeNoneAjaxVo> list = organizationService.selectTreeOrganizationChildren(condition);
        if (StringUtils.isNotBlank(id)) {
            return JsonMapper.nonEmptyMapper().toJsonP(callback, list.get(0).getChildren());
        }
        return JsonMapper.nonEmptyMapper().toJsonP(callback, list);
    }

}
